<template>
  <div class="schedule-handle">
    <el-form 
      ref="scheduleFormRef"
      :model="scheduleForm" 
      :rules="scheduleRules"
      label-width="100px"
    >
      <el-form-item label="科室" prop="departmentId">
        <el-tree-select 
          v-model="scheduleForm.departmentId" 
          placeholder="请选择科室"
          @change="handleDepartmentChange"
          style="width: 100%"
          :data="departmentTree"
          node-key="id"
          :props="{
            label: 'name',
            value: 'id',
            children: 'children'
          }"
          check-strictly
          clearable
          filterable
        />
      </el-form-item>
      <el-form-item label="医生" prop="doctorId">
        <el-select 
          v-model="scheduleForm.doctorId" 
          placeholder="请选择医生"
          style="width: 100%"
          :disabled="!scheduleForm.departmentId"
        >
          <el-option
            v-for="doctor in doctorList"
            :key="doctor.id"
            :label="doctor.name"
            :value="doctor.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排班日期" prop="scheduleDate">
        <el-date-picker
          v-model="scheduleForm.scheduleDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="时段" prop="timeSlot">
        <el-select v-model="scheduleForm.timeSlot" placeholder="请选择时段" style="width: 100%">
          <el-option label="上午" :value="1" />
          <el-option label="下午" :value="2" />
          <el-option label="晚上" :value="3" />
        </el-select>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-time-picker
              v-model="scheduleForm.startTime"
              placeholder="选择时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-time-picker
              v-model="scheduleForm.endTime"
              placeholder="选择时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="可预约数量" prop="availableCount">
        <el-input-number 
          v-model="scheduleForm.availableCount" 
          :min="1" 
          :max="100"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="挂号费用" prop="registrationFee">
        <el-input-number 
          v-model="scheduleForm.registrationFee" 
          :min="0" 
          :precision="2"
          :step="5"
          style="width: 100%"
        >
          <template #prefix>¥</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="scheduleForm.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        {{ isEdit ? '更新' : '创建' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { createSchedule, updateSchedule } from '@/api/business'
import { getDepartmentTree, getDepartmentDoctors } from '@/api/business'

// Props接收
const props = defineProps({
  scheduleData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emit定义
const emit = defineEmits(['close'])

// 响应式数据
const submitLoading = ref(false)
const departmentTree = ref([])
const doctorList = ref([])

// 表单引用
const scheduleFormRef = ref()

// 排班表单
const scheduleForm = reactive({
  id: null,
  departmentId: null,
  doctorId: null,
  scheduleDate: '',
  timeSlot: null,
  startTime: '',
  endTime: '',
  availableCount: 20,
  registrationFee: 0.00,
  remark: ''
})

// 表单验证规则
const scheduleRules = {
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }],
  doctorId: [{ required: true, message: '请选择医生', trigger: 'change' }],
  scheduleDate: [{ required: true, message: '请选择排班日期', trigger: 'change' }],
  timeSlot: [{ required: true, message: '请选择时段', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  availableCount: [{ required: true, message: '请输入可预约数量', trigger: 'blur' }],
  registrationFee: [
    { required: true, message: '请输入挂号费用', trigger: 'blur' },
    { type: 'number', min: 0, message: '挂号费用不能小于0', trigger: 'blur' }
  ]
}

// 获取科室树形数据
const fetchDepartmentList = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentTree.value = response.data || []
    }
  } catch (error) {
    console.error('获取科室树形数据失败:', error)
  }
}

// 处理科室选择变更
const handleDepartmentChange = async (departmentId) => {
  if (!departmentId) {
    doctorList.value = []
    scheduleForm.doctorId = null
    return
  }
  try {
    const response = await getDepartmentDoctors(departmentId)
    if (response.code === 200) {
      doctorList.value = response.data || []
    }
  } catch (error) {
    console.error('获取科室医生列表失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await scheduleFormRef.value.validate()
    submitLoading.value = true
    
    let response
    if (props.isEdit) {
      // 编辑模式调用更新接口
      response = await updateSchedule(scheduleForm)
    } else {
      // 创建模式调用创建接口
      response = await createSchedule(scheduleForm)
    }
    
    if (response.code === 200) {
      ElMessage.success(props.isEdit ? '更新成功' : '创建成功')
      emit('close', 'success') // 传递成功标识
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  emit('close', 'cancel')
}

// 初始化表单数据
const initFormData = () => {
  Object.assign(scheduleForm, {
    id: null,
    departmentId: null,
    doctorId: null,
    scheduleDate: '',
    timeSlot: null,
    startTime: '',
    endTime: '',
    availableCount: 20,
    registrationFee: 0.00,
    remark: ''
  })

  // 如果是编辑模式，填充数据
  if (props.isEdit && props.scheduleData) {
    Object.assign(scheduleForm, { ...props.scheduleData })
    if (props.scheduleData.departmentId) {
      handleDepartmentChange(props.scheduleData.departmentId)
    }
  }
}

// 监听props变化
watch(() => props.scheduleData, () => {
  initFormData()
}, { immediate: true, deep: true })

// 生命周期
onMounted(() => {
  fetchDepartmentList()
  initFormData()
})
</script>

<style scoped>
.schedule-handle {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}
</style> 